import logging
import json
import paho.mqtt.client as client


class Mqttclient:
    def __init__(self, config: dict) -> None:
        super().__init__()
        global _log
        _log = logging.getLogger('mqttclient')
        self._hostConfig = config.get('mqtt')
        self._uptopic = config.get("upTopic")

    def _on_connect(self, client, userdata, flags, result_code, *extra_params):
        if result_code == 0:
            _log.info('连接 %s:%s - successfully.',
                      self._hostConfig["host"], self._hostConfig["port"])
        else:
            _log.error(f"Mqttclient connection FAIL with error:{result_code}!")

    def _on_disconnect(self, client, userdata, reasonCode):
        _log.info("断开连接 %s", self._hostConfig["host"])

    def _on_message(self, client, userdata, message):
        _log.info("收到消息:client = %s, userdata = %s, message = %s",
                  client, userdata, message)

    # 发送mqtt消息
    def send_Msg(self, topic: str = None, msg: dict = None):
        paylods = json.dumps(msg)
        self._client.publish(topic, paylods)

    def start(self):
        try:
            self._client = client.Client()
            self._client.connect(self._hostConfig['host'],
                                 self._hostConfig.get('port', 1883))
            if "user" in self._hostConfig:
                self._client.username_pw_set(
                    self._hostConfig["user"], self._hostConfig["password"])
            # mqtt 回调处理
            self._client.on_connect = self._on_connect
            self._client.on_message = self._on_message
            self._client.on_disconnect = self._on_disconnect
            self._client.loop_start()
        except ConnectionRefusedError as e:
            _log.error(e)

    def stop(self):
        self._client.loop_stop()
        self._client.disconnect()
        _log.info("mqttclient Stoped")
